
import { ProColumns, ProTable } from '@ant-design/pro-components';
import '@umijs/max';
import {GetProp, message, Modal, Select, Upload, UploadProps} from 'antd';
import React, {useEffect, useState} from 'react';
import {updateEmpByIdUsingPut} from "@/services/tlias-backend/empController";
import {selectDeptIdAndNameUsingGet} from "@/services/tlias-backend/deptController";
import {uploadImageUsingPost} from "@/services/tlias-backend/uploadController";
import {PlusOutlined} from "@ant-design/icons";


type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];

const beforeUpload = (file: FileType) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('只能上传 JPG/PNG 格式的文件!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('图片大小要小于 2MB!');
  }
  return isJpgOrPng && isLt2M;
};

interface Props {
  oldData?: API.Emp;
  visible: boolean;
  columns: ProColumns<API.Emp>[];
  onSubmit: (values: API.EmpEditDTO) => void;
  onCancel: () => void;
}

/**
 * 更新节点
 *
 * @param fields
 */
const handleUpdate = async (fields: API.EmpEditDTO) => {
  const hide = message.loading('正在更新');
  try {
    // 更新员工信息
    await updateEmpByIdUsingPut(fields);
    hide();
    message.success('更新成功');
    return true;
  } catch (error: any) {
    hide();
    message.error('更新失败，' + error.message);
    return false;
  }
};

/**
 * 更新弹窗
 * @param props
 * @constructor
 */
const UpdateModal: React.FC<Props> = (props) => {
  const { oldData, visible, columns, onSubmit, onCancel } = props;
  const [deptList, setDeptList] = useState<{ id: number; name: string }[]>([]);
  const [imageUrl, setImageUrl] = useState<string | undefined>(oldData?.image);

  useEffect(() => {
    if (visible && oldData?.image) {
      setImageUrl(oldData.image); // 如果有原始图片 URL，设置到 state 中
    }
    if (visible) {
      selectDeptIdAndNameUsingGet().then((response) => {
        if (response.code === 200) {
          setDeptList(response.data as any);
        } else {
          message.error('获取部门列表失败');
        }
      });
    }
  }, [visible]);

  if (!oldData) {
    return <></>;
  }

  // 更新 columns，处理 image 字段
  const updatedColumns = columns.map((column) => {
    if (column.dataIndex === 'deptId') {
      return {
        ...column,
        renderFormItem: (item: any, { type, defaultRender, ...rest }: any, form: any) => {
          if (type === 'form') {
            return (
              <Select
                placeholder="请选择部门"
                options={deptList.map((dept) => ({
                  label: dept.name,
                  value: dept.id,
                }))}
                onChange={(value) => {
                  form.setFieldsValue({ deptId: value });
                }}
              />
            );
          }
          return defaultRender(item);
        },
      };
    }

    // 如果是 image 字段，替换为图片上传组件
    if (column.dataIndex === 'image') {
      return {
        ...column,
        renderFormItem: (item: any, { type, defaultRender, ...rest }: any, form: any) => {
          if (type === 'form') {
            return (
              <Upload
                name="avatar"
                listType="picture-card"
                showUploadList={true}
                beforeUpload={beforeUpload}
                customRequest={async (options) => {
                  const { file, onSuccess, onError } = options;
                  const formData = new FormData();
                  formData.append('file', file);

                  try {
                    const response = await uploadImageUsingPost(formData as any);
                    if (response.code === 200) {
                      const imageUrl = response.data;  // 假设返回的数据中有图片的 URL
                      setImageUrl(imageUrl as any);
                      form.setFieldsValue({ image: imageUrl });
                      onSuccess?.(imageUrl);
                    } else {
                      message.error('上传失败');
                      onError?.(new Error('上传失败'));
                    }
                  } catch (error) {
                    message.error('上传失败');
                    onError?.(error as any);
                  }
                }}
                onChange={(info) => {
                  if (info.file.status === 'done') {
                    // 更新图片URL
                    form.setFieldsValue({ image: info.file.response });
                  }
                }}
              >
                {imageUrl ? (
                  <img src={imageUrl} alt="avatar" style={{ width: '100%' }} />
                ) : (
                  <div>
                    {<PlusOutlined />}
                    <div style={{ marginTop: 8 }}>上传头像</div>
                  </div>
                )}
              </Upload>
            );
          }
          return defaultRender(item);
        },
      };
    }

    return column;
  });

  return (
    <Modal
      destroyOnClose
      title={'更新'}
      open={visible}
      footer={null}
      onCancel={() => {
        onCancel?.();
      }}
    >
      <ProTable
        type="form"
        columns={updatedColumns}
        form={{
          initialValues: oldData,
        }}
        onSubmit={async (values: API.EmpEditDTO) => {
          // 提交时确保 image 字段是 URL 字符串
          // if (values.image && typeof values.image !== 'string') {
          //   values.image = values.image?.fileList?.[0]?.response || '';
          // }
          const success = await handleUpdate({
            ...values,
            id: oldData.id as any,
          });
          if (success) {
            onSubmit?.(values);
          }
        }}
      />
    </Modal>
  );
};

export default UpdateModal;
